package handlers.echo;

import handlers.ConnectionHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import domain.ValueStore;

public class InMemoryKeyValueStoreHandler implements ConnectionHandler {
    
    private static final int BUFSIZE = 100;   // Size of receive buffer
    private ValueStore store= new ValueStore();
    
    @Override
    public void handle(final Socket s) throws IOException {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        
        int recvMsgSize;   // Size of received message
        byte[] receiveBuf = new byte[BUFSIZE];  // Receive buffer

        // Receive until client closes connection, indicated by -1 return
        while ((recvMsgSize = in.read(receiveBuf)) != -1) {
          byte[] ans=processRequest(receiveBuf,recvMsgSize);
          out.write(ans, 0, ans.length);
          ans=null;
        }
        
        s.close();  // Close the socket.  We are done with this client!
        System.out.println( "se desconecto el cliente");
    }
    
    public byte[] processRequest(byte[] request,int sizeRequest){
    	String resp="";
    	
    	String[] commandLine=new String(request,0,sizeRequest).replace("\n","").split(" ");
    	
    	if(commandLine==null || commandLine.length==0){
    		resp="";
    	}else{
    		String command=commandLine[0];
    		
    		if(command.equals("ALL")){
    			HashMap<String,AtomicInteger> hash=store.getAll();
    			if (!hash.isEmpty()){
    				Set<String>keys=hash.keySet();
    				for(String k:keys){
    					resp+= k +","+ hash.get(k) + "\n";
    				}
    			} else{
    				resp= "empty store";
    			}
    		} else if(command.equals("INC")){
    			if( commandLine.length < 3){
    				resp="invalid command";
    			}else{
    				store.increment(commandLine[1],Integer.valueOf(commandLine[2]));
    			}
    		}else if(command.equals("DEC")){
    			if( commandLine.length < 3){
    				resp="invalid command";
    			}else{
    				store.decrement(commandLine[1],Integer.valueOf(commandLine[2]));
    			}
    			
    		}else if(command.equals("GET")){
    			if( commandLine.length <2 ){
    				resp="invalid command";
    			}else{
    				try{
    					resp="value:"+store.get(commandLine[1]);
    				}catch (Exception e) {
    					resp="no value";
    				}
    			}
    		}else if(command.equals("ADD")){
    			if( commandLine.length < 3){
    				resp="invalid command";
    			}else{
    				store.set(commandLine[1],Integer.valueOf(commandLine[2]));
    				resp="stored";
    			}
    		}else{
    			resp="unkown command";
    		}
    	}
    	
    	resp+="\n";
    	
    	return resp.getBytes();
    }
}
